<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { Bell, Calendar, ChatDotRound, Warning, Delete } from '@element-plus/icons-vue'
import { getDoctorMessages, readDoctorMessage, readAllDoctorMessages, deleteDoctorMessage } from '@/apis/doctor/doctorMessageAPI'
import { getDoctorAppointmentMessages, readAllDoctorAppointmentMessages, readDoctorAppointmentMessage, deleteDoctorAppointmentMessage } from '@/apis/doctor/doctorAppointmentAPI'
import type { Message } from '@/types/message'
import { messageTypeMap } from '@/types/message'
import { ElMessage } from 'element-plus'

// 消息列表
const messageList = ref<Message[]>([])
// 总消息数
const total = ref(0)
// 未读消息数
const unreadCount = ref(0)
// 当前页
const currentPage = ref(1)
// 每页数量
const pageSize = ref(10)
// 加载状态
const loading = ref(false)
// 当前选中的消息类型
const activeType = ref(0) // 0表示全部
// 当前选中的消息状态
const activeStatus = ref(-1) // -1表示全部，0表示未读，1表示已读
// 当前选中的消息
const selectedMessage = ref<Message | null>(null)
// 是否显示消息详情
const showDetail = ref(false)

// 消息类型列表
const messageTypes = [
  { value: 0, label: '全部消息' },
  { value: 1, label: '系统消息' },
  { value: 2, label: '预约消息' },
  { value: 3, label: '问诊消息' },
  { value: 4, label: '紧急消息' }
]

// 消息状态列表
const messageStatuses = [
  { value: -1, label: '全部' },
  { value: 0, label: '未读' },
  { value: 1, label: '已读' }
]

// 获取消息图标
const getMessageIcon = (type: number) => {
  switch (type) {
    case 1:
      return Bell
    case 2:
      return Calendar
    case 3:
      return ChatDotRound
    case 4:
      return Warning
    default:
      return Bell
  }
}

// 获取消息列表
const fetchMessages = async () => {
  loading.value = true
  try {
    const params: any = {
      page: currentPage.value,
      pageSize: pageSize.value
    }

    // 如果选择了特定状态，添加状态过滤
    if (activeStatus.value !== -1) {
      params.status = activeStatus.value
    }

    let res

    // 根据消息类型调用不同的API
    if (activeType.value === 2) { // 预约消息
      res = await getDoctorAppointmentMessages(params)
    } else {
      // 如果选择了特定类型（非预约消息），添加类型过滤
      if (activeType.value !== 0) {
        params.type = activeType.value
      }
      res = await getDoctorMessages(params)
    }

    if (res.code === 200) {
      messageList.value = res.data.list || []
      total.value = res.data.total || 0
      unreadCount.value = res.data.unreadCount || 0
    } else {
      ElMessage.error(res.message || '获取消息失败')
    }
  } catch (error) {
    console.error('获取消息列表出错:', error)
    ElMessage.error('获取消息列表失败')
  } finally {
    loading.value = false
  }
}

// 切换消息类型
const changeMessageType = (type: number) => {
  activeType.value = type
  currentPage.value = 1
  fetchMessages()
}

// 切换消息状态
const changeMessageStatus = (status: number) => {
  activeStatus.value = status
  currentPage.value = 1
  fetchMessages()
}

// 查看消息详情
const viewMessageDetail = async (message: Message) => {
  selectedMessage.value = message
  showDetail.value = true

  // 如果消息未读，标记为已读
  if (message.status === 0) {
    try {
      // 根据消息类型调用不同的API
      if (activeType.value === 2) { // 预约消息
        await readDoctorAppointmentMessage(message.id)
      } else {
        await readDoctorMessage(message.id)
      }

      // 更新消息状态
      message.status = 1
      // 更新未读消息数
      if (unreadCount.value > 0) {
        unreadCount.value--
      }
      // 如果当前在未读消息筛选下，需要重新获取列表
      if (activeStatus.value === 0) {
        fetchMessages()
      }
    } catch (error) {
      console.error('标记消息已读出错:', error)
    }
  }
}

// 返回消息列表
const backToList = () => {
  showDetail.value = false
  selectedMessage.value = null
}

// 全部标记为已读
const markAllAsRead = async () => {
  try {
    let res

    // 根据当前选中的消息类型调用不同的API
    if (activeType.value === 2) { // 预约消息
      res = await readAllDoctorAppointmentMessages()
    } else {
      res = await readAllDoctorMessages()
    }

    if (res.code === 200) {
      ElMessage.success('全部标记为已读')
      // 更新消息状态
      messageList.value.forEach(msg => {
        msg.status = 1
      })
      // 更新未读消息数
      unreadCount.value = 0
      // 如果当前在未读消息筛选下，需要重新获取列表
      if (activeStatus.value === 0) {
        fetchMessages()
      }
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('标记全部已读出错:', error)
    ElMessage.error('操作失败')
  }
}

// 删除消息
const deleteMessage = async (message: Message, event?: Event) => {
  if (event) {
    event.stopPropagation()
  }

  try {
    let res

    // 根据消息类型调用不同的API
    if (activeType.value === 2) { // 预约消息
      res = await deleteDoctorAppointmentMessage(message.id)
    } else {
      res = await deleteDoctorMessage(message.id)
    }

    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 从列表中移除
      messageList.value = messageList.value.filter(msg => msg.id !== message.id)
      // 如果当前查看的是这条消息，返回列表
      if (selectedMessage.value && selectedMessage.value.id === message.id) {
        backToList()
      }
      // 如果是未读消息，更新未读数
      if (message.status === 0 && unreadCount.value > 0) {
        unreadCount.value--
      }
      // 更新总数
      if (total.value > 0) {
        total.value--
      }
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    console.error('删除消息出错:', error)
    ElMessage.error('删除失败')
  }
}

// 页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchMessages()
}

// 每页数量变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchMessages()
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 监听消息类型变化，重新获取消息
watch(activeType, () => {
  currentPage.value = 1
  fetchMessages()
})

// 组件挂载时获取消息列表
onMounted(() => {
  fetchMessages()
})
</script>

<template>
  <div class="message-page-container">
    <el-card class="message-card">
      <template #header>
        <div class="card-header">
          <h2 class="header-title">消息中心</h2>
          <div class="header-actions">
            <el-button type="primary" @click="markAllAsRead">全部标记为已读</el-button>
          </div>
        </div>
      </template>

      <div class="message-content">
        <!-- 消息筛选区域 -->
        <div class="filter-container">
          <div class="filter-group">
            <span class="filter-label">消息类型：</span>
            <div class="filter-options">
              <el-radio-group v-model="activeType" @change="changeMessageType">
                <el-radio-button
                  v-for="type in messageTypes"
                  :key="type.value"
                  :label="type.value"
                >
                  {{ type.label }}
                </el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <div class="filter-group">
            <span class="filter-label">消息状态：</span>
            <div class="filter-options">
              <el-radio-group v-model="activeStatus" @change="changeMessageStatus">
                <el-radio-button
                  v-for="status in messageStatuses"
                  :key="status.value"
                  :label="status.value"
                >
                  {{ status.label }}
                </el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </div>

        <!-- 消息列表/详情区域 -->
        <div class="message-main-content">
          <!-- 消息列表 -->
          <div v-if="!showDetail" class="message-list-container">
            <el-table
              v-loading="loading"
              :data="messageList"
              style="width: 100%"
              @row-click="viewMessageDetail"
            >
              <el-table-column width="60">
                <template #default="{ row }">
                  <el-icon :style="{ color: messageTypeMap[row.type]?.color, fontSize: '20px' }">
                    <component :is="getMessageIcon(row.type)" />
                  </el-icon>
                </template>
              </el-table-column>

              <el-table-column prop="title" label="标题">
                <template #default="{ row }">
                  <div class="message-title-cell">
                    <span>{{ row.title }}</span>
                    <el-tag v-if="row.status === 0" size="small" type="danger" effect="plain">未读</el-tag>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="type" label="类型" width="120">
                <template #default="{ row }">
                  <el-tag
                    :style="{ color: messageTypeMap[row.type]?.color, borderColor: messageTypeMap[row.type]?.color }"
                    effect="plain"
                  >
                    {{ messageTypeMap[row.type]?.label }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column prop="createTime" label="时间" width="180">
                <template #default="{ row }">
                  {{ formatTime(row.createTime) }}
                </template>
              </el-table-column>

              <el-table-column width="80">
                <template #default="{ row }">
                  <el-button
                    type="danger"
                    size="small"
                    circle
                    @click.stop="deleteMessage(row, $event)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>

          <!-- 消息详情 -->
          <div v-else class="message-detail-container">
            <div class="detail-header">
              <el-button @click="backToList">
                <el-icon><arrow-left /></el-icon> 返回列表
              </el-button>
            </div>

            <div v-if="selectedMessage" class="detail-content">
              <div class="detail-title">
                <h3>{{ selectedMessage.title }}</h3>
                <div class="detail-meta">
                  <el-tag
                    :style="{ color: messageTypeMap[selectedMessage.type]?.color, borderColor: messageTypeMap[selectedMessage.type]?.color }"
                    effect="plain"
                  >
                    {{ messageTypeMap[selectedMessage.type]?.label }}
                  </el-tag>
                  <span class="detail-time">{{ formatTime(selectedMessage.createTime) }}</span>
                </div>
              </div>

              <div class="detail-body">
                <p>{{ selectedMessage.content }}</p>
              </div>

              <div class="detail-footer">
                <el-button type="danger" @click="deleteMessage(selectedMessage)">删除消息</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.message-page-container {
  padding: 20px;
}

.message-card {
  width: 100%;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }
}

.filter-container {
  margin-bottom: 20px;

  .filter-group {
    margin-bottom: 15px;
    display: flex;
    align-items: center;

    .filter-label {
      width: 80px;
      font-weight: 500;
    }

    .filter-options {
      flex: 1;
    }
  }
}

.message-title-cell {
  display: flex;
  align-items: center;

  span {
    margin-right: 10px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.message-detail-container {
  .detail-header {
    margin-bottom: 20px;
  }

  .detail-content {
    .detail-title {
      margin-bottom: 20px;

      h3 {
        margin: 0 0 10px 0;
        font-size: 20px;
        font-weight: 600;
      }

      .detail-meta {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #909399;

        .detail-time {
          margin-left: 15px;
        }
      }
    }

    .detail-body {
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 4px;
      min-height: 200px;
      margin-bottom: 20px;

      p {
        line-height: 1.8;
        margin: 0;
        font-size: 15px;
      }
    }
  }
}
</style>
